<script setup>
import _ from 'lodash'
import {onMounted, reactive, ref, toRefs, watch} from "vue";
import {api} from "@jzl/api";

const FORM_DFT = {
  loginname: '',
  nickname: '',
  avatar: null,
  type: 'MGR',
  roles: []
};
const emit = defineEmits(['close'])
const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  modId: {
    type: Number,
    default: null
  },
  isView: {
    type: Boolean,
    default: false
  }
})

const {
  form,
  formLabelWidth,
  // winName,
  // items,
  loading,
  roles,
  rules,
} = toRefs(reactive({
  formLabelWidth: '120px',
  // winName: '新增',
  // items: [],
  loading: false,

  form: _.cloneDeep(FORM_DFT),
  roles: [],
  rules: {
    loginname: [
      {required: true, message: '请输入登录名', trigger: 'blur'}
    ],
    nickname: [
      {required: true, message: '请输入昵称', trigger: 'blur'}
    ]
  }
}))
const mformRef = ref(null)
watch(() => props.show, (val) => {
  if (val) {
    this.init();
  }
})

onMounted(() => {
  init();
})

const init = async () => {
  form.value = _.cloneDeep(FORM_DFT);
  mformRef.value?.resetFields();

  let data = await api.role.getRoleList();

  if (data) {
    roles.value = data;
  }

  if (props.modId) {
    let admin = await api.adminmgr.getById(props.modId);
    if (admin) {
      form.value.id = admin.id;
      form.value.loginname = admin.loginname;
      form.value.nickname = admin.nickname;
      form.value.avatar = admin.avatar;
      form.type = admin.type;
      formatRoles(admin.roles);
      // this.form.roles = [];
    } else {
      $jui.toast('操作失败，请稍后再试！');
    }
  }
}

const formatRoles = (roles) => {

  let roleKeys = [];
  if (roles && roles.length) {
    for (let i = 0; i < roles.length; i++) {
      let it = roles[i];
      roleKeys.push(it.id);
    }
  }

  form.value.roles = roleKeys;
}

const submit = () => {

  mformRef.value.validate((valid) => {
    if (valid) {
      _submit();
    } else {
      return false;
    }
  });
}

const _submit = async () => {
  let ret;

  loading.value = true;
  if (props.modId && form.value.id) {
    ret = await api.admin.updateAdmin(form.value.id, form.value);
  } else {
    ret = await api.admin.createAdmin(form.value);
  }

  loading.value = false;

  if (ret) {
    close(true);
    $jui.toast('操作成功！');
  }
}

const close = (flag) => {
  emit('close', flag);
}

const handleAvatarChange = (file) => {
  let val = _.cloneDeep(file);

  if (val) {
    val.value = _.get(file, "file_path");
    val.file_id = _.get(file, "id");
  }

  _.assign(form.value.avatar, val);
}
</script>

<template>
  <el-form
    :model="form"
    ref="mformRef"
    :rules="rules"
    style="min-width:500px;"
    :label-width="formLabelWidth"
  >
    <el-form-item label="登录名" prop="loginname">
      <el-input v-model="form.loginname" autocomplete="off" style="width:280px;" :disabled="isView"></el-input>
    </el-form-item>
    <!--<el-form-item label="手机号" prop="mobile">
        <el-input v-model="form.mobile" autocomplete="off" style="width:280px;" :disable="isView"></el-input>
    </el-form-item>-->
    <!--<el-form-item label="初始化密码" prop="password">
        <el-input v-model="form.password" autocomplete="off" style="width:280px;"></el-input>
    </el-form-item>-->
    <el-form-item label="昵称" prop="nickname">
      <el-input
        v-model="form.nickname"
        autocomplete="off"
        style="width:280px;"
        :disabled="isView"></el-input>
    </el-form-item>

    <el-form-item label="头像" prop="avatar">
      <FilePicker
        :is-view="isView"
        :info="form.avatar"
        @change="handleAvatarChange"
      ></FilePicker>
      <!--  v-model="form.avatar" -->
    </el-form-item>

    <!--<el-form-item label="类型" prop="type">
        <template v-if="isView">
            {{ form.type | adminTypeLabel}}
        </template>
        <el-radio-group v-else v-model="form.type" :disabled="isView">
            <el-radio label="DATA">管理员</el-radio>
            <el-radio label="SUPER" :disabled="loginUser && loginUser.type === '_SUPER' ? false: true">超级管理员</el-radio>
        </el-radio-group>
    </el-form-item>-->
    <el-form-item label="角色" prop="roles" v-if="form.type != 'SUPER' && form.type != '_SUPER'">
      <el-select v-model="form.roles" multiple placeholder="请选择" :disabled="isView">
        <el-option v-for="item in roles" :key="item.id" :label="item.name" :value="item.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item v-if="isView">
      <el-button type="primary" @click="close()" size="medium">确 定</el-button>
    </el-form-item>
    <el-form-item v-else>
      <el-button type="primary" @click="submit()" size="medium">确 定</el-button>
      <el-button @click="close()" size="medium">取 消</el-button>
    </el-form-item>
  </el-form>
</template>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
